package com.aiatomic.countlib;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

class ReadHelper {
    public static String read(InputStream inputStream) {
        try {
            byte[] lengthBytes = read(inputStream, 4);
            int len = byte2Int(lengthBytes);
            try {
                byte[] bytesBody = read(inputStream, len);
                String body = new String(bytesBody, StandardCharsets.UTF_8);
                return body.trim();
            } catch (OutOfMemoryError | NegativeArraySizeException error) {
                error.printStackTrace();
                return "";
            }
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }

    public static Bitmap readBitmap(InputStream inputStream) {
        try {
            byte[] lengthBytes = read(inputStream, 4);
            int len = byte2Int(lengthBytes);
            try {
                byte[] bytesBody = read(inputStream, len);
                return BitmapFactory.decodeByteArray(bytesBody, 0, bytesBody.length);
            } catch (OutOfMemoryError | NegativeArraySizeException error) {
                error.printStackTrace();
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private static byte[] read(InputStream is, int len) throws IOException {
        byte[] bytes = new byte[len];
        int offset = 0;
        int readLen = len;
        int realReadLen = 0;
        while (realReadLen < len) {
            if (is == null) {
                break;
            }
            int currentRead = is.read(bytes, offset, readLen);
            if (currentRead != -1) {
                realReadLen += currentRead;
                offset = realReadLen;
                readLen = len - offset;
            } else {
                break;
            }
        }
        return bytes;
    }

    private static int byte2Int(byte[] b) {
        int intValue = 0;
        for (int i = 0; i < b.length; i++) {
            intValue += (b[i] & 0xFF) << (8 * (3 - i));
        }
        return intValue;
    }
}
